import boto3
from datetime import datetime
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# [profile Qa]
# aws_access_key_id = "AKIASWZL2UIXMPQQ4NFT"
# aws_secret_access_key = "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"
#
# [profile Prod]
aws_access_key_id = "AKIAVGNWUKMQCF2NKKNR"
aws_secret_access_key = "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"

# 定义每页返回的项目数量
page_size = 500

# 定义初始化分页参数
start_key = None

# aws auth
table_name = 'oauth2-authentication-info'

aws_region = 'us-east-2'

session = boto3.Session(
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    region_name=aws_region
)
dynamodb = session.client('dynamodb', region_name=aws_region)


def get_timestamp_from_code(code):
    # Assuming the timestamp is after the colon in the "code" field
    timestamp_str = code.split(':')[1].strip()
    timestamp_int = 0
    if len(timestamp_str) == 13:
        # Convert from milliseconds to seconds
        timestamp_int = int(timestamp_str) // 1000
    elif len(timestamp_str) == 10:
        timestamp_int = int(timestamp_str)
    else:
        logger.error(f"Invalid timestamp format{code}")
    return datetime.utcfromtimestamp(timestamp_int).isoformat()


def get_timestamp_for_token(auth_infos):
    return get_timestamp_from_code(auth_infos['code']['S'])


def delete_old_tokens():
    # Get all unique user_ids
    global start_key
    while True:
        if start_key:
            response = dynamodb.scan(
                TableName=table_name,
                Limit=page_size,
                ExclusiveStartKey=start_key
            )
        else:
            response = dynamodb.scan(
                TableName=table_name,
                Limit=page_size
            )
        tokens = response.get('Items', [])
        logger.info(f"记录数量:{len(tokens)}")
        # 从tokens列表中提取唯一的user_id
        user_ids = [token['user_id']['S'] for token in tokens]
        # 将user_ids列表转换为集合
        unique_user_ids = set(user_ids)
        logger.info(f"用户数量:{len(unique_user_ids)}")
        # Process each user_id
        while len(unique_user_ids) > 0:
            user_id = unique_user_ids.pop()
            historical_datas = dynamodb.query(
                TableName=table_name,
                IndexName='user_id-type-index',
                KeyConditionExpression='user_id = :uid',
                ExpressionAttributeValues={':uid': {'S': user_id}}
            )
            if len(historical_datas['Items']) > 1:
                # Sort tokens by timestamp in descending order
                sorted_tokens = sorted(historical_datas['Items'], key=get_timestamp_for_token, reverse=True)
                # Keep the latest token and delete the others
                # latest_token = sorted_tokens[0]
                for token in sorted_tokens[1:]:
                    try:
                        dynamodb.delete_item(
                            TableName=table_name,
                            Key={'code': token['code']}
                        )
                        logger.info(f"Deleted old token for user {user_id}: {token['code']}")
                    except Exception as e:
                        logger.error(f"Error deleting token for user {user_id}: {token['code']} Error: {e}")
                        continue
        start_key = response.get('LastEvaluatedKey')
        if not start_key:
            logger.info('执行完成!')
            break


delete_old_tokens()
